<?php

namespace backend\models;

use common\models\HtCommon;
use Yii;

/**
 * This is the model class for table "{{%oplog}}".
 *
 * @property int $id 主键
 * @property int $uid 用户
 * @property string $router 访问地址
 * @property string $router_name 操作名
 * @property string $param 数据
 * @property string $ip
 * @property string $address 操作地址
 * @property int $create_time 操作时间
 */
class Oplog extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return '{{%oplog}}';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['uid', 'router', 'router_name', 'param', 'ip', 'address'], 'required'],
            [['uid', 'create_time'], 'integer'],
            [['router', 'router_name', 'address'], 'string', 'max' => 100],
            [['param'], 'string', 'max' => 500],
            [['ip'], 'string', 'max' => 50],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => '主键',
            'uid' => '用户',
            'router' => '访问地址',
            'router_name' => '操作名',
            'param' => '数据',
            'ip' => 'Ip',
            'address' => '操作地址',
            'create_time' => '操作时间',
        ];
    }

    /**关联用户**/
    public function getUser()
    {
        return $this->hasOne(User::className(),['id'=>'uid']);
    }

    /**
     * 操作日志添加
     * @param $uid
     * @param $route
     * @param $route_name
     * @param $param
     */
    public static function opLog($uid, $route, $route_name, $param)
    {
        $model = new Oplog();
        $model->uid = $uid;
        $model->router = $route;
        $model->router_name = $route_name;
        $model->param = json_encode($param);
        $model->ip = Yii::$app->request->userIP;
        $model->address = HtCommon::getAddress($model->ip);
        $model->create_time = time();
        $model->save();
    }
}
